package com.raja.servingStation.common.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.raja.servingStation.common.exception.BusinessRuntimeException;
import com.raja.servingStation.common.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by liuyanjun
 * on 2017/7/21.
 */
@Component
public class CheckCodeUtil {

    Cache<String, Integer> poiCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.HOURS).maximumSize(200).build();
    Cache<String, String> poiCodeCache = CacheBuilder.newBuilder().expireAfterAccess(120, TimeUnit.SECONDS).maximumSize(200).build();

    private static int timeOut = 120;

    @Value("${verifyCode.limit-count}")
    private Integer limitCount;
    /**
     * 从缓存取出code
     * @param uniqueClient
     * @return
     * @throws Exception
     */
    public  String checkCode(String uniqueClient) throws Exception{
        String key = "servingStation."+uniqueClient+".code.value";
        String checkCode = RedisUtil.getString(key);
        RedisUtil.delKeys(key);
        return checkCode;
    }

    public  void setKey(String uniqueClient, String verification) throws Exception {
        String key = "servingStation."+uniqueClient+".code.value";
        RedisUtil.setString(key,timeOut,verification+"");
    }

    public  void checkIpVistTimes(String ip) throws Exception {
        String key = "servingStation."+ip+".count";
        Integer count = poiCache.getIfPresent(key);
        count = count == null?0:count;
        //如果访问的次数大于了限制的次数
        if(limitCount > Integer.valueOf(count)){
            poiCache.put(key, Integer.valueOf(count)+1);
        }else {
            throw  new BusinessRuntimeException(ErrorCode.VIST_COUNT_TOO_MANAY);
        }
    }

    public void setCacheKey(String uniqueClient, String verifyCode) {
        String key = "servingStation."+uniqueClient+".code.value";
        poiCodeCache.put(key, verifyCode);
    }
    public String getCacheKey(String uniqueClient) {
        String key = "servingStation."+uniqueClient+".code.value";
        return  poiCodeCache.getIfPresent(key);
    }
}
